package com.jinzecloud.reportapproval.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.deepoove.poi.config.Configure;
import com.deepoove.poi.data.Pictures;
import com.deepoove.poi.plugin.table.LoopColumnTableRenderPolicy;
import com.deepoove.poi.plugin.table.LoopRowTableRenderPolicy;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import com.jinzecloud.reportapproval.bean.*;
import com.jinzecloud.reportapproval.enums.AuditRoleEnums;
import com.jinzecloud.reportapproval.enums.StateEnum;
import com.jinzecloud.reportapproval.enums.TableEnums;
import com.jinzecloud.reportapproval.enums.UserStateEnum;
import com.jinzecloud.reportapproval.dto.AdminDto;
import com.jinzecloud.reportapproval.dto.Param;
import com.jinzecloud.reportapproval.mapper.AdminMapper;
import com.jinzecloud.reportapproval.service.*;
import com.jinzecloud.reportapproval.utils.*;
import com.jinzecloud.reportapproval.vo.*;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.jinzecloud.reportapproval.mapper.ReportMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;


@Service("reportService")
public class ReportServiceImpl extends ServiceImpl<ReportMapper, Report> implements ReportService {

    @Autowired
    private ReportConditionService reportConditionService;
    @Autowired
    private ReportCheckResultService reportCheckResultService;
    @Autowired
    private ReportSampleConsResultsService reportSampleConsResultsService;
    @Autowired
    private ReportSampleSafetyResultsService reportSampleSafetyResultsService;
    @Autowired
    private ReportConsResultsService reportConsResultsService;
    @Autowired
    private ReportSampleSuitResultsService reportSampleSuitResultsService;
    @Autowired
    private ReportSampleConsSuitResultsService reportSampleConsSuitResultsService;
    @Autowired
    private ReportReliabilityResultService reportReliabilityResultService;
    @Autowired
    private ReportReliabilityConsResultService reportReliabilityConsResultService;
    @Autowired
    private AdminMapper adminMapper;
    @Autowired
    private ReportMapper reportMapper;
    @Autowired
    private ProductServiceImpl productService;
    @Autowired
    private FileUploadUtil fileUploadUtil;
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private TemperatureHumidityService temperatureHumidityService;
    @Autowired
    private SoilFirmnessMoistureService soilFirmnessMoistureService;
    @Autowired
    private ConsCheckRecordService consCheckRecordService;
    @Autowired
    private DeepStabilityRecordServiceImpl deepStabilityRecordService;
    @Autowired
    private VegetationRecordFormServiceImpl vegetationRecordFormService;
    @Autowired
    private BreakageRateServiceImpl breakageRateService;
    @Autowired
    private UserSurveySummaryService userSurveySummaryService;
    @Autowired
    private SafetyAssessmentService safetyAssessmentService;
    @Autowired
    private SampleSheetService sampleSheetService;


    @Override
    public PageUtils queryPage(Param param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String adminUserName = authentication.getName();
        MPJLambdaWrapper<Admin> adminWrapper = new MPJLambdaWrapper<>();
        adminWrapper
                .select(Admin::getAdId, Admin::getAdUserName, Admin::getAdName)
                .select(RoleEntity::getRoleName)
                .leftJoin(RoleUserEntity.class, RoleUserEntity::getUserId, Admin::getAdId)
                .leftJoin(RoleEntity.class, RoleEntity::getRoleId, RoleUserEntity::getRoleId)
                .eq(Admin::getAdUserName, adminUserName);
        String pageSize = param.getPage();
        String limit = param.getLimit();
        String key = param.getKey();
        Map<String, Object> params = new HashMap<>();
        params.put("page", pageSize);
        params.put("limit", limit);
        MPJLambdaWrapper<Report> reportMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reportMPJLambdaWrapper.selectAll(Report.class);
        if (!StringUtils.isEmpty(key)) {
            reportMPJLambdaWrapper.eq(Report::getId, key).or()
                    .like(Report::getProductName, key).or();
        }
        IPage<ReportCheckVo> page = reportMapper.selectJoinPage(
                new Page<>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit"))),
                ReportCheckVo.class,
                reportMPJLambdaWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<ReportCheckVo> records = page.getRecords();
        List<ReportCheckVo> collect = records.stream()
                .map(productInfoVo -> {
                    String reprotStatus = productInfoVo.getReprotStatus();
                    productInfoVo.setApprovalOpinion(AuditUtil.getStateText(TableEnums.REPORT_AND_PRODUCT_INFO.getTableName(), Integer.parseInt(reprotStatus)).getDesc());
                    return productInfoVo;
                }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public R saveReport(Report report) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String adminUserName = authentication.getName();
        QueryWrapper<Admin> adminQueryWrapper = new QueryWrapper<>();
        adminQueryWrapper.eq("ad_user_name", adminUserName);
        Admin admin = adminMapper.selectOne(adminQueryWrapper);
        report.setReprotStatus(String.valueOf(StateEnum.UN_SUBMIT.getState()));
        report.setReportWriter(admin.getAdSignature());
        QueryWrapper<Report> reportQueryWrapper = new QueryWrapper<>();
        reportQueryWrapper.eq("product_number", report.getProductNumber());
        List<Report> list = list(reportQueryWrapper);
        if (list.size() >= 1) return R.error("编号：" + report.getProductNumber() + "已存在，请勿重复添加！");
        reportMapper.insert(report);
        return R.ok();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateByIdReportVo(ReportVo reportVo) {
        Report report = new Report();
        BeanUtils.copyProperties(reportVo, report);
        report.setReprotStatus(String.valueOf(StateEnum.UN_SUBMIT.getState()));
        reportMapper.updateById(report);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void removeByIdsReportVo(List<Integer> list) {

    }

    @Override
    public String fileDownload(String id) {
        ReportExportVo reportExportVo = this.getByIdReportExportVo(Integer.parseInt(id));
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        Product product = new Product();
        BeanUtils.copyProperties(reportExportVo, product);
        Report report = this.getById(reportExportVo.getId());
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(product));
        data.putAll(JSONObject.parseObject(JSONObject.toJSONString(reportExportVo)));
        if (StrUtil.isNotEmpty(data.getString("approver"))) data.put("approver", Pictures.ofUrl(data.getString("approver")).size(30, 10).create());
        if (StrUtil.isNotEmpty(data.getString("auditor"))) data.put("auditor", Pictures.ofUrl(data.getString("auditor")).size(30, 10).create());
        if (StrUtil.isNotEmpty(data.getString("reportWriter"))) data.put("reportWriter", Pictures.ofUrl(data.getString("reportWriter")).size(30, 10).create());
        if (StrUtil.isNotEmpty(data.getString("reportChecker"))) data.put("reportChecker", Pictures.ofUrl(data.getString("reportChecker")).size(30, 10).create());
        if (StrUtil.isNotEmpty(data.getString("projectLeader"))) data.put("projectLeader", Pictures.ofUrl(data.getString("projectLeader")).size(30, 10).create());
        List<ReportConditionVo> reportConditionVo = reportExportVo.getReportConditionVo();
        List<ReportCheckResultVo> reportCheckResultVo = reportExportVo.getReportCheckResultVo();
        List<ReportSampleConsResultsVo> reportSampleSonsResultsVo = reportExportVo.getReportSampleSonsResultsVo();
        List<ReportSampleSafetyResultsVo> reportSampleSafetyResultsVo = reportExportVo.getReportSampleSafetyResultsVo();
        List<ReportConsResultsVo> reportConsResultsVo = reportExportVo.getReportConsResultsVo();
        List<ReportSampleSuitResultsVo> reportSampleSuitResultsVo = reportExportVo.getReportSampleSuitResultsVo();
        List<ReportSampleConsSuitResultsVo> reportSampleConsSuitResultsVo = reportExportVo.getReportSampleConsSuitResultsVo();
        List<ReportReliabilityResultVo> reportReliabilityResultVo = reportExportVo.getReportReliabilityResultVo();
        List<ReportReliabilityConsResultVo> reportReliabilityConsResultVo = reportExportVo.getReportReliabilityConsResultVo();
        data.put("reportConditionVo", reportConditionVo);
        data.put("reportCheckResultVo", reportCheckResultVo);
        data.put("reportSampleSonsResultsVo", reportSampleSonsResultsVo);
        data.put("reportSampleSafetyResultsVo", reportSampleSafetyResultsVo);
        data.put("reportConsResultsVo", reportConsResultsVo);
        data.put("reportSampleSuitResultsVo", reportSampleSuitResultsVo);
        data.put("reportSampleConsSuitResultsVo", reportSampleConsSuitResultsVo);
        data.put("reportReliabilityResultVo", reportReliabilityResultVo);
        data.put("reportReliabilityConsResultVo", reportReliabilityConsResultVo);

        File tempFile = WordUtil.getWordFile("template/productInfo.docx", data, Configure.builder()
                .bind("reportConditionVo", policy)
                .bind("reportCheckResultVo", policy)
                .bind("reportSampleSonsResultsVo", policy)
                .bind("reportSampleSafetyResultsVo", policy)
                .bind("reportConsResultsVo", policy)
                .bind("reportSampleSuitResultsVo", policy)
                .bind("reportSampleConsSuitResultsVo", policy)
                .bind("reportReliabilityResultVo", policy)
                .bind("reportReliabilityConsResultVo", policy));
        if (tempFile == null) return null;
        String fileName = "农业机械检验报告";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + report.getProductName() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() +fileName;
        FileUtil.copyFile(tempFile, new File(filePath + ".docx"));
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<Report>().set(Report::getReportPath, savePath + ".docx").set(Report::getPdfPath, savePath + ".pdf").eq(Report::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() + fileName + ".docx";
    }

    @Override
    public R updateApprovalOpinion(ReporteUpdateCheckVo reporteUpdateCheckVo) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        Report report = this.getById(reporteUpdateCheckVo.getId());
        int state = Integer.parseInt(report.getReprotStatus());
        List<AdminDto> adminDos = AuditUtil.getAdminDto(authentication.getName());
        if (CollectionUtil.isEmpty(adminDos)) return R.error("您没有审核权限！");
        if (!reporteUpdateCheckVo.isReprotStatus()) {
            updateById(report.setReprotStatus(String.valueOf(StateEnum.APPROVAL_NOT_PASS.getState()))
                    .setApprovalOpinion(reporteUpdateCheckVo.getAuditOpinion())
                    .setDateOfApproval(DateUtil.date()));
            return R.ok();
        }
        StateEnum currentAuditState = AuditUtil.getStateText(TableEnums.REPORT_AND_PRODUCT_INFO.getTableName(), state);
        Integer nextAuditStateIndex = AuditUtil.getNextAuditState(TableEnums.REPORT_AND_PRODUCT_INFO.getTableName(), state, adminDos.stream().map(AdminDto::getRoleCode).toList());
        AdminDto adminDto = adminDos.stream().filter(a -> StrUtil.equals(a.getRoleName(), currentAuditState.getAuditRole()))
                .findFirst().orElse(null);
        if (adminDto == null || nextAuditStateIndex == null) return R.error("您没有审核权限！");
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.WRITER.getCode())) report.setReportWriter(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.APPROVER.getCode())) report.setApprover(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.AUDITOR.getCode())) report.setAuditor(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.PRINCIPAL.getCode())) report.setProjectLeader(adminDto.getAdSignature());
        if (StrUtil.equals(adminDto.getRoleCode(), AuditRoleEnums.CHECKER.getCode())) report.setReportChecker(adminDto.getAdSignature());
        report.setReprotStatus(String.valueOf(nextAuditStateIndex))
                .setAuditor(adminDto.getAdSignature())
                .setApprovalOpinion(reporteUpdateCheckVo.getAuditOpinion())
                .setDateOfApproval(DateUtil.date());
        updateById(report);
        return R.ok();
    }

    @Override
    public PageUtils queryPageCheckList(Param param) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        String adminUserName = authentication.getName();
        MPJLambdaWrapper<Admin> adminWrapper = new MPJLambdaWrapper<>();
        adminWrapper
                .select(Admin::getAdId, Admin::getAdUserName, Admin::getAdName)
                .select(RoleEntity::getRoleName)
                .leftJoin(RoleUserEntity.class, RoleUserEntity::getUserId, Admin::getAdId)
                .leftJoin(RoleEntity.class, RoleEntity::getRoleId, RoleUserEntity::getRoleId)
                .eq(Admin::getAdUserName, adminUserName);
        List<AdminDto> adminDtoList = adminMapper.selectJoinList(AdminDto.class, adminWrapper);
        String pageSize = param.getPage();
        String limit = param.getLimit();
        String key = param.getKey();
        Map<String, Object> params = new HashMap<>();
        params.put("page", pageSize);
        params.put("limit", limit);
        MPJLambdaWrapper<Report> reportMPJLambdaWrapper = new MPJLambdaWrapper<>();
        reportMPJLambdaWrapper
                .selectAll(Report.class);
        if (!StringUtils.isEmpty(key)) {
            reportMPJLambdaWrapper.eq(Report::getId, key).or()
                    .like(Report::getProductName, key).or();
        }
        Set<Integer> stateSet = adminDtoList.stream().map(adminDo ->
                StateEnum.getStateEnumByAuditRole(adminDo.getRoleCode()).getState()).collect(Collectors.toSet());
        if (stateSet.contains(StateEnum.UN_SUBMIT.getState())) {
            // TODO 只能看见自己编辑的逻辑
//            productInfoMPJLambdaWrapper.and(wrapper -> wrapper.eq(ProductInfo::getReprotStatus, StateEnum.SUBMIT.getState()).eq(ProductInfo::get));
            stateSet.add(StateEnum.APPROVAL_PASS.getState());
//            stateSet.remove(StateEnum.SUBMIT.getState());
        }

        IPage<ReportCheckVo> page = reportMapper.selectJoinPage(
                new Page<>(Long.parseLong((String) params.get("page")), Long.parseLong((String) params.get("limit"))),
                ReportCheckVo.class,
                reportMPJLambdaWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<ReportCheckVo> records = page.getRecords();
        List<ReportCheckVo> collect = records.stream()
                .peek(productInfoVo -> {
                    String reprotStatus = productInfoVo.getReprotStatus();
                    productInfoVo.setApprovalOpinion(AuditUtil.getStateText(TableEnums.REPORT_AND_PRODUCT_INFO.getTableName(), Integer.parseInt(reprotStatus)).getDesc());
                }).collect(Collectors.toList());
        pageUtils.setList(collect);
        return pageUtils;
    }

    @Override
    public ReportVos getByIdReportVo(Integer id) {
        Report report = this.getById(id);
        ReportVos reportVos = new ReportVos();
        if (report != null) {
            BeanUtils.copyProperties(report, reportVos);
        }
        QueryWrapper<ReportCondition> reportConditionQueryWrapper = new QueryWrapper<>();
        reportConditionQueryWrapper.eq("report_id", report.getId());
        List<ReportCondition> reportConditionVos = reportConditionService.list(reportConditionQueryWrapper);
        List<ReportConditionVo> reportConditionVosList = reportConditionVos.stream().map(reportCondition -> {
            ReportConditionVo reportConditionVo1 = new ReportConditionVo();
            BeanUtils.copyProperties(reportCondition, reportConditionVo1);
            return reportConditionVo1;
        }).collect(Collectors.toList());
        reportVos.setReportConditionVo(reportConditionVosList);
        QueryWrapper<ReportConsResults> reportConsResultsQueryWrapper = new QueryWrapper<>();
        reportConsResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportConsResults> reportConsResultsVos = reportConsResultsService.list(reportConsResultsQueryWrapper);
        List<ReportConsResultsVo> reportConsResultsVosList = reportConsResultsVos.stream().map(reportConsResults -> {
            ReportConsResultsVo reportConsResultsVo = new ReportConsResultsVo();
            BeanUtils.copyProperties(reportConsResults, reportConsResultsVo);
            return reportConsResultsVo;
        }).collect(Collectors.toList());
        reportVos.setReportConsResultsVo(reportConsResultsVosList);
        QueryWrapper<ReportCheckResult> reportCheckResultQueryWrapper = new QueryWrapper<>();
        reportCheckResultQueryWrapper.eq("report_id", report.getId());
        List<ReportCheckResult> reportCheckResults = reportCheckResultService.list(reportCheckResultQueryWrapper);
        List<ReportCheckResultVo> reportCheckResultVosList = reportCheckResults.stream().map(reportCheckResult -> {
            ReportCheckResultVo reportCheckResultVo = new ReportCheckResultVo();
            BeanUtils.copyProperties(reportCheckResult, reportCheckResultVo);
            return reportCheckResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportCheckResultVo(reportCheckResultVosList);
        QueryWrapper<ReportSampleConsResults> reportSampleConsResultsQueryWrapper = new QueryWrapper<>();
        reportSampleConsResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleConsResults> reportSampleConsResultsVos = reportSampleConsResultsService.list(reportSampleConsResultsQueryWrapper);
        List<ReportSampleConsResultsVo> reportSampleConsResultsVosList = reportSampleConsResultsVos.stream().map(reportSampleConsResults -> {
            ReportSampleConsResultsVo reportSampleConsResultsVo = new ReportSampleConsResultsVo();
            BeanUtils.copyProperties(reportSampleConsResults, reportSampleConsResultsVo);
            return reportSampleConsResultsVo;
        }).collect(Collectors.toList());
        reportVos.setReportSampleSonsResultsVo(reportSampleConsResultsVosList);
        QueryWrapper<ReportSampleSafetyResults> reportSampleSafetyResultsQueryWrapper = new QueryWrapper<>();
        reportSampleSafetyResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleSafetyResults> reportSampleSafetyResultsVos = reportSampleSafetyResultsService.list(reportSampleSafetyResultsQueryWrapper);
        List<ReportSampleSafetyResultsVo> reportSampleSafetyResultsVosList = reportSampleSafetyResultsVos.stream().map(reportSampleSafetyResults -> {
            ReportSampleSafetyResultsVo reportSampleSafetyResultsVo = new ReportSampleSafetyResultsVo();
            BeanUtils.copyProperties(reportSampleSafetyResults, reportSampleSafetyResultsVo);
            return reportSampleSafetyResultsVo;
        }).collect(Collectors.toList());
        if (reportSampleSafetyResultsVosList.size() > 0) {
            reportVos.setReportSampleSafetyResultsVo(reportSampleSafetyResultsVosList);
        }
        QueryWrapper<ReportSampleSuitResults> reportSampleSuitResultsQueryWrapper = new QueryWrapper<>();
        reportSampleSuitResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleSuitResults> reportSampleSuitResultsVos = reportSampleSuitResultsService.list(reportSampleSuitResultsQueryWrapper);
        List<ReportSampleSuitResultsVo> reportSampleSuitResultsVosList = reportSampleSuitResultsVos.stream().map(reportSampleSuitResults -> {
            ReportSampleSuitResultsVo reportSampleSuitResultsVo = new ReportSampleSuitResultsVo();
            BeanUtils.copyProperties(reportSampleSuitResults, reportSampleSuitResultsVo);
            return reportSampleSuitResultsVo;
        }).collect(Collectors.toList());
        reportVos.setReportSampleSuitResultsVo(reportSampleSuitResultsVosList);
        QueryWrapper<ReportSampleConsSuitResults> reportSampleConsSuitResultsQueryWrapper = new QueryWrapper<>();
        reportSampleConsSuitResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleConsSuitResults> reportSampleConsSuitResultsVos = reportSampleConsSuitResultsService.list(reportSampleConsSuitResultsQueryWrapper);
        List<ReportSampleConsSuitResultsVo> reportSampleConsSuitResultsVosList = reportSampleConsSuitResultsVos.stream().map(reportSampleConsSuitResults -> {
            ReportSampleConsSuitResultsVo reportSampleConsSuitResultsVo = new ReportSampleConsSuitResultsVo();
            BeanUtils.copyProperties(reportSampleConsSuitResults, reportSampleConsSuitResultsVo);
            return reportSampleConsSuitResultsVo;
        }).collect(Collectors.toList());
        if (reportSampleConsSuitResultsVosList.size() > 0) {
            reportVos.setReportSampleConsSuitResultsVo(reportSampleConsSuitResultsVosList);
        }
        QueryWrapper<ReportReliabilityResult> reportReliabilityResultQueryWrapper = new QueryWrapper<>();
        reportReliabilityResultQueryWrapper.eq("report_id", report.getId());
        List<ReportReliabilityResult> reportReliabilityResultVos = reportReliabilityResultService.list(reportReliabilityResultQueryWrapper);
        List<ReportReliabilityResultVo> reportReliabilityResultVosList = reportReliabilityResultVos.stream().map(reportReliabilityResult -> {
            ReportReliabilityResultVo reportReliabilityResultVo = new ReportReliabilityResultVo();
            BeanUtils.copyProperties(reportReliabilityResult, reportReliabilityResultVo);
            return reportReliabilityResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportReliabilityResultVo(reportReliabilityResultVosList);
        QueryWrapper<ReportReliabilityConsResult> reportReliabilityConsResultVos = new QueryWrapper<>();
        reportReliabilityConsResultVos.eq("report_id", report.getId());
        List<ReportReliabilityConsResult> reportReliabilityConsResultVosList = reportReliabilityConsResultService.list(reportReliabilityConsResultVos);
        List<ReportReliabilityConsResultVo> collect = reportReliabilityConsResultVosList.stream().map(reportReliabilityConsResult -> {
            ReportReliabilityConsResultVo reportReliabilityConsResultVo = new ReportReliabilityConsResultVo();
            BeanUtils.copyProperties(reportReliabilityConsResult, reportReliabilityConsResultVo);
            return reportReliabilityConsResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportReliabilityConsResultVo(collect);
        return reportVos;
    }

    @Override
    public R fileUplod(String id, MultipartFile file) throws IOException {
        String s = "";
        if (FileUtil.getSuffix(file.getOriginalFilename()).equals("docx")) {
            s = fileUploadUtil.validateFile(file, "WD");
        } else {
            s = fileUploadUtil.validateFile(file, "TP");
        }

        if (s != null) {
            return R.error(s);
        }
        String suffix = FileUtil.getSuffix(file.getOriginalFilename());
        String fileName = StrUtil.uuid().replaceAll("-", "") + "." + suffix;
        String path = fileUploadUtil.getUploadFilePath("tp") + fileName;
        System.out.println(path);
        file.transferTo(FileUtil.file(path));
        return R.ok().put("data", RequestUtils.getBasePath(request) + "upload/tp/" + fileName);
    }

    @Override
    public ReportExportVo getByIdReportExportVo(Integer id) {
        Report report = this.getById(id);
        ReportExportVo reportVos = new ReportExportVo();
        if (report != null) {
            BeanUtils.copyProperties(report, reportVos);
        }
        QueryWrapper<ReportCondition> reportConditionQueryWrapper = new QueryWrapper<>();
        reportConditionQueryWrapper.eq("report_id", report.getId());
        List<ReportCondition> reportConditionVos = reportConditionService.list(reportConditionQueryWrapper);
        List<ReportConditionVo> reportConditionVosList = reportConditionVos.stream().map(reportCondition -> {
            ReportConditionVo reportConditionVo1 = new ReportConditionVo();
            BeanUtils.copyProperties(reportCondition, reportConditionVo1);
            return reportConditionVo1;
        }).collect(Collectors.toList());
        reportVos.setReportConditionVo(reportConditionVosList);
        QueryWrapper<ReportCheckResult> reportCheckResultQueryWrapper = new QueryWrapper<>();
        reportCheckResultQueryWrapper.eq("report_id", report.getId());
        List<ReportCheckResult> reportCheckResults = reportCheckResultService.list(reportCheckResultQueryWrapper);
        List<ReportCheckResultVo> reportCheckResultVosList = reportCheckResults.stream().map(reportCheckResult -> {
            ReportCheckResultVo reportCheckResultVo = new ReportCheckResultVo();
            BeanUtils.copyProperties(reportCheckResult, reportCheckResultVo);
            return reportCheckResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportCheckResultVo(reportCheckResultVosList);
        QueryWrapper<ReportSampleConsResults> reportSampleConsResultsQueryWrapper = new QueryWrapper<>();
        reportSampleConsResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleConsResults> reportSampleConsResultsVos = reportSampleConsResultsService.list(reportSampleConsResultsQueryWrapper);
        List<ReportSampleConsResultsVo> reportSampleConsResultsVosList = reportSampleConsResultsVos.stream().map(reportSampleConsResults -> {
            ReportSampleConsResultsVo reportSampleConsResultsVo = new ReportSampleConsResultsVo();
            BeanUtils.copyProperties(reportSampleConsResults, reportSampleConsResultsVo);
            return reportSampleConsResultsVo;
        }).collect(Collectors.toList());
        reportVos.setReportSampleSonsResultsVo(reportSampleConsResultsVosList);
        QueryWrapper<ReportSampleSafetyResults> reportSampleSafetyResultsQueryWrapper = new QueryWrapper<>();
        reportSampleSafetyResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleSafetyResults> reportSampleSafetyResultsVos = reportSampleSafetyResultsService.list(reportSampleSafetyResultsQueryWrapper);
        List<ReportSampleSafetyResultsVo> reportSampleSafetyResultsVosList = reportSampleSafetyResultsVos.stream().map(reportSampleSafetyResults -> {
            ReportSampleSafetyResultsVo reportSampleSafetyResultsVo = new ReportSampleSafetyResultsVo();
            BeanUtils.copyProperties(reportSampleSafetyResults, reportSampleSafetyResultsVo);
            return reportSampleSafetyResultsVo;
        }).collect(Collectors.toList());
        if (reportSampleSafetyResultsVosList.size() > 0) {
            reportVos.setReportSampleSafetyResultsVo(reportSampleSafetyResultsVosList);
        }
        QueryWrapper<ReportSampleSuitResults> reportSampleSuitResultsQueryWrapper = new QueryWrapper<>();
        reportSampleSuitResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleSuitResults> reportSampleSuitResultsVos = reportSampleSuitResultsService.list(reportSampleSuitResultsQueryWrapper);
        List<ReportSampleSuitResultsVo> reportSampleSuitResultsVosList = reportSampleSuitResultsVos.stream().map(reportSampleSuitResults -> {
            ReportSampleSuitResultsVo reportSampleSuitResultsVo = new ReportSampleSuitResultsVo();
            BeanUtils.copyProperties(reportSampleSuitResults, reportSampleSuitResultsVo);
            return reportSampleSuitResultsVo;
        }).collect(Collectors.toList());
        reportVos.setReportSampleSuitResultsVo(reportSampleSuitResultsVosList);
        QueryWrapper<ReportSampleConsSuitResults> reportSampleConsSuitResultsQueryWrapper = new QueryWrapper<>();
        reportSampleConsSuitResultsQueryWrapper.eq("report_id", report.getId());
        List<ReportSampleConsSuitResults> reportSampleConsSuitResultsVos = reportSampleConsSuitResultsService.list(reportSampleConsSuitResultsQueryWrapper);
        List<ReportSampleConsSuitResultsVo> reportSampleConsSuitResultsVosList = reportSampleConsSuitResultsVos.stream().map(reportSampleConsSuitResults -> {
            ReportSampleConsSuitResultsVo reportSampleConsSuitResultsVo = new ReportSampleConsSuitResultsVo();
            BeanUtils.copyProperties(reportSampleConsSuitResults, reportSampleConsSuitResultsVo);
            return reportSampleConsSuitResultsVo;
        }).collect(Collectors.toList());
        if (reportSampleConsSuitResultsVosList.size() > 0) {
            reportVos.setReportSampleConsSuitResultsVo(reportSampleConsSuitResultsVosList);
        }
        QueryWrapper<ReportReliabilityResult> reportReliabilityResultQueryWrapper = new QueryWrapper<>();
        reportReliabilityResultQueryWrapper.eq("report_id", report.getId());
        List<ReportReliabilityResult> reportReliabilityResultVos = reportReliabilityResultService.list(reportReliabilityResultQueryWrapper);
        List<ReportReliabilityResultVo> reportReliabilityResultVosList = reportReliabilityResultVos.stream().map(reportReliabilityResult -> {
            ReportReliabilityResultVo reportReliabilityResultVo = new ReportReliabilityResultVo();
            BeanUtils.copyProperties(reportReliabilityResult, reportReliabilityResultVo);
            return reportReliabilityResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportReliabilityResultVo(reportReliabilityResultVosList);
        QueryWrapper<ReportReliabilityConsResult> reportReliabilityConsResultVos = new QueryWrapper<>();
        reportReliabilityConsResultVos.eq("report_id", report.getId());
        List<ReportReliabilityConsResult> reportReliabilityConsResultVosList = reportReliabilityConsResultService.list(reportReliabilityConsResultVos);
        List<ReportReliabilityConsResultVo> collect = reportReliabilityConsResultVosList.stream().map(reportReliabilityConsResult -> {
            ReportReliabilityConsResultVo reportReliabilityConsResultVo = new ReportReliabilityConsResultVo();
            BeanUtils.copyProperties(reportReliabilityConsResult, reportReliabilityConsResultVo);
            return reportReliabilityConsResultVo;
        }).collect(Collectors.toList());
        reportVos.setReportReliabilityConsResultVo(collect);
        return reportVos;
    }

    @Override
    public String getReportFilePath(String id) {
        Report report = getById(id);
        if (StrUtil.isEmpty(report.getPdfPath()) || StrUtil.isEmpty(report.getReportPath())){
            fileDownload(id);
            report = getById(id);
            return report.getPdfPath();
        }
        return report.getPdfPath();
    }

    @Override
    public String viewPdf(Integer id) {
        ReportVoes reportVoes = new ReportVoes();
        Report report = this.getById(id);
        String projectNumber = report.getProductNumber();
        BeanUtils.copyProperties(report, reportVoes);
        reportVoes.setProjectNumber(projectNumber);
        reportVoes.setSampleType(report.getSampleType());
        List<SampleDetails> sampleDetails = sampleSheetService.getProductNumber(projectNumber);
        //温度
        TemperatureHumidity temperatureHumidity = temperatureHumidityService.getProductNumber(projectNumber);
        //土壤坚实度、土壤含水率
        SoilFirmnessMoisture soilFirmnessMoisture = soilFirmnessMoistureService.getProductNumber(projectNumber);
        //一致性检查记录表
        ConsCheckRecord consCheckRecord = consCheckRecordService.getProductNumber(projectNumber);
        //耕深
        DeepStabilityRecord deepStabilityRecord = deepStabilityRecordService.getProductNumber(projectNumber);
        //植被覆盖率
        VegetationRecordForm vegetationRecordForm = vegetationRecordFormService.getProductNumber(projectNumber);
        //碎土率测定
        BreakageRate breakagerate = breakageRateService.getProductNumber(projectNumber);
        //安全性检查
        SafetyAssessment safetyAssessment = safetyAssessmentService.getProductNumber(projectNumber);
        reportVoes.setHasSafetyDevice(safetyAssessment.getHasSafetyDevice()?"是":"否");
        reportVoes.setJudgmentResult(safetyAssessment.getJudgmentResult());
        reportVoes.setOverlapLength(safetyAssessment.getOverlapLength());
        reportVoes.setIsShieldEnveloping(safetyAssessment.getIsShieldEnveloping()?"是":"否");
        reportVoes.setWorkingWidth(safetyAssessment.getWorkingWidth());
        reportVoes.setHasClutchProtection(safetyAssessment.getHasClutchProtection()?"是":"否");
        reportVoes.setJudgmentResultClutch(safetyAssessment.getJudgmentResultClutch());
        reportVoes.setMeetsRequirements(safetyAssessment.getMeetsRequirements()?"是":"否");
        reportVoes.setHasFrontProtection(safetyAssessment.getHasFrontProtection()?"是":"否");
        reportVoes.setFrontExtensionDistance(safetyAssessment.getFrontExtensionDistance());
        reportVoes.setGroundClearanceHeight(safetyAssessment.getGroundClearanceHeight());
        reportVoes.setProtectiveFences(safetyAssessment.getProtectiveFences());
        reportVoes.setJudgmentResultFront(safetyAssessment.getJudgmentResultFront());
        reportVoes.setHasEndProtection(safetyAssessment.getHasEndProtection()?"是":"否");
        reportVoes.setSideExtensionDistance(safetyAssessment.getSideExtensionDistance());
        reportVoes.setCanCoverAboveGround(safetyAssessment.getCanCoverAboveGround()?"是":"否");
        reportVoes.setFenceGap(safetyAssessment.getFenceGap());
        reportVoes.setJudgmentResultFence(safetyAssessment.getJudgmentResultFence());
        reportVoes.setCoversOuterArea(safetyAssessment.getCoversOuterArea()?"是":"否");
        reportVoes.setJudgmentResultOuterArea(safetyAssessment.getJudgmentResultOuterArea());
        reportVoes.setCoversWholePart(safetyAssessment.getCoversWholePart()?"是":"否");
        reportVoes.setJudgmentResultWholePart(safetyAssessment.getJudgmentResultWholePart());
        reportVoes.setHasStabilizingMeasures(safetyAssessment.getHasStabilizingMeasures());
        reportVoes.setJudgmentResultStabilizing(safetyAssessment.getJudgmentResultStabilizing());
        reportVoes.setHasWarningLabel(safetyAssessment.getHasWarningLabel()?"是":"否");
        reportVoes.setCompliesGb10396(safetyAssessment.getCompliesGb10396());
        reportVoes.setJudgmentResultGb(safetyAssessment.getJudgmentResultGb());
        reportVoes.setHasSafetyNotes(safetyAssessment.getHasSafetyNotes()?"是":"否");
        reportVoes.setInUserManual(safetyAssessment.getInUserManual()?"是":"否");
        reportVoes.setJudgmentResultManual(safetyAssessment.getJudgmentResultManual());
        reportVoes.setJudgmentResultManual(safetyAssessment.getJudgmentResultManual());
        reportVoes.setModel1(sampleDetails.get(0).getSampleNumber());
        reportVoes.setModel3(sampleDetails.get(0).getAppearanceNumber());
        reportVoes.setModel2(sampleDetails.get(1).getSampleNumber());
        reportVoes.setModel4(sampleDetails.get(1).getAppearanceNumber());


        //用户满意度
        UserSurveySummary userSurveySummary = userSurveySummaryService.getProductNumber(projectNumber);
        reportVoes.setTemperature(temperatureHumidity.getTemperatureRange());
        reportVoes.setHumidity(temperatureHumidity.getHumidityRange());
        reportVoes.setConsistency(soilFirmnessMoisture.getSoilAvg());
        reportVoes.setContaining(soilFirmnessMoisture.getWaterAvg());
        reportVoes.setConsCheckRecord(consCheckRecord.getConsCheckRecordInfoList());
        reportVoes.setDepth(deepStabilityRecord.getAvg());
        reportVoes.setStability(deepStabilityRecord.getSc());
        reportVoes.setCrushedSoil(breakagerate.getCrushedSoil());
        reportVoes.setVegetationCoverage(vegetationRecordForm.getCoverage());
        reportVoes.setApplicability(userSurveySummary.getRemark());
        reportVoes.setUserSatisfaction(userSurveySummary.getUserState());
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(reportVoes));
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        File tempFile = WordUtil.getWordFile("template/reprot.docx", data, Configure.builder().bind("consCheckRecord", policy));
        String fileName = "推广检验报告";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + report.getProductName() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"),true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<Report>().set(Report::getReportPath, savePath + ".docx").set(Report::getPdfPath, savePath + ".pdf").eq(Report::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() + fileName + ".pdf";
    }

    @Override
    public String viewWord(Integer id) {
        ReportVoes reportVoes = new ReportVoes();
        Report report = this.getById(id);
        String projectNumber = report.getProductNumber();
        BeanUtils.copyProperties(report, reportVoes);
        reportVoes.setProjectNumber(projectNumber);
        reportVoes.setSampleType(report.getSampleType());
        List<SampleDetails> sampleDetails = sampleSheetService.getProductNumber(projectNumber);
        //温度
        TemperatureHumidity temperatureHumidity = temperatureHumidityService.getProductNumber(projectNumber);
        //土壤坚实度、土壤含水率
        SoilFirmnessMoisture soilFirmnessMoisture = soilFirmnessMoistureService.getProductNumber(projectNumber);
        //一致性检查记录表
        ConsCheckRecord consCheckRecord = consCheckRecordService.getProductNumber(projectNumber);
        //耕深
        DeepStabilityRecord deepStabilityRecord = deepStabilityRecordService.getProductNumber(projectNumber);
        //植被覆盖率
        VegetationRecordForm vegetationRecordForm = vegetationRecordFormService.getProductNumber(projectNumber);
        //碎土率测定
        BreakageRate breakagerate = breakageRateService.getProductNumber(projectNumber);
        //安全性检查
        SafetyAssessment safetyAssessment = safetyAssessmentService.getProductNumber(projectNumber);
        reportVoes.setHasSafetyDevice(safetyAssessment.getHasSafetyDevice()?"是":"否");
        reportVoes.setJudgmentResult(safetyAssessment.getJudgmentResult());
        reportVoes.setOverlapLength(safetyAssessment.getOverlapLength());
        reportVoes.setIsShieldEnveloping(safetyAssessment.getIsShieldEnveloping()?"是":"否");
        reportVoes.setWorkingWidth(safetyAssessment.getWorkingWidth());
        reportVoes.setHasClutchProtection(safetyAssessment.getHasClutchProtection()?"是":"否");
        reportVoes.setJudgmentResultClutch(safetyAssessment.getJudgmentResultClutch());
        reportVoes.setMeetsRequirements(safetyAssessment.getMeetsRequirements()?"是":"否");
        reportVoes.setHasFrontProtection(safetyAssessment.getHasFrontProtection()?"是":"否");
        reportVoes.setFrontExtensionDistance(safetyAssessment.getFrontExtensionDistance());
        reportVoes.setGroundClearanceHeight(safetyAssessment.getGroundClearanceHeight());
        reportVoes.setProtectiveFences(safetyAssessment.getProtectiveFences());
        reportVoes.setJudgmentResultFront(safetyAssessment.getJudgmentResultFront());
        reportVoes.setHasEndProtection(safetyAssessment.getHasEndProtection()?"是":"否");
        reportVoes.setSideExtensionDistance(safetyAssessment.getSideExtensionDistance());
        reportVoes.setCanCoverAboveGround(safetyAssessment.getCanCoverAboveGround()?"是":"否");
        reportVoes.setFenceGap(safetyAssessment.getFenceGap());
        reportVoes.setJudgmentResultFence(safetyAssessment.getJudgmentResultFence());
        reportVoes.setCoversOuterArea(safetyAssessment.getCoversOuterArea()?"是":"否");
        reportVoes.setJudgmentResultOuterArea(safetyAssessment.getJudgmentResultOuterArea());
        reportVoes.setCoversWholePart(safetyAssessment.getCoversWholePart()?"是":"否");
        reportVoes.setJudgmentResultWholePart(safetyAssessment.getJudgmentResultWholePart());
        reportVoes.setHasStabilizingMeasures(safetyAssessment.getHasStabilizingMeasures());
        reportVoes.setJudgmentResultStabilizing(safetyAssessment.getJudgmentResultStabilizing());
        reportVoes.setHasWarningLabel(safetyAssessment.getHasWarningLabel()?"是":"否");
        reportVoes.setCompliesGb10396(safetyAssessment.getCompliesGb10396());
        reportVoes.setJudgmentResultGb(safetyAssessment.getJudgmentResultGb());
        reportVoes.setHasSafetyNotes(safetyAssessment.getHasSafetyNotes()?"是":"否");
        reportVoes.setInUserManual(safetyAssessment.getInUserManual()?"是":"否");
        reportVoes.setJudgmentResultManual(safetyAssessment.getJudgmentResultManual());
        reportVoes.setJudgmentResultManual(safetyAssessment.getJudgmentResultManual());
        reportVoes.setModel1(sampleDetails.get(0).getSampleNumber());
        reportVoes.setModel3(sampleDetails.get(0).getAppearanceNumber());
        reportVoes.setModel2(sampleDetails.get(1).getSampleNumber());
        reportVoes.setModel4(sampleDetails.get(1).getAppearanceNumber());


        //用户满意度
        UserSurveySummary userSurveySummary = userSurveySummaryService.getProductNumber(projectNumber);
        reportVoes.setTemperature(temperatureHumidity.getTemperatureRange());
        reportVoes.setHumidity(temperatureHumidity.getHumidityRange());
        reportVoes.setConsistency(soilFirmnessMoisture.getSoilAvg());
        reportVoes.setContaining(soilFirmnessMoisture.getWaterAvg());
        reportVoes.setConsCheckRecord(consCheckRecord.getConsCheckRecordInfoList());
        reportVoes.setDepth(deepStabilityRecord.getAvg());
        reportVoes.setStability(deepStabilityRecord.getSc());
        reportVoes.setCrushedSoil(breakagerate.getCrushedSoil());
        reportVoes.setVegetationCoverage(vegetationRecordForm.getCoverage());
        reportVoes.setApplicability(userSurveySummary.getRemark());
        reportVoes.setUserSatisfaction(userSurveySummary.getUserState());
        JSONObject data = JSONObject.parseObject(JSONObject.toJSONString(reportVoes));
        LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
        File tempFile = WordUtil.getWordFile("template/reprot.docx", data, Configure.builder().bind("consCheckRecord", policy));
        String fileName = "推广检验报告";
        String uploadDirectory = fileUploadUtil.getUploadFilePath("temp");
        String filePath = uploadDirectory + report.getProductName() + fileName;
        String savePath = RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() +fileName;
        FileUtil.copy(tempFile, new File(filePath + ".docx"),true);
        PDFUtil.WordToPdf(tempFile, new File(filePath + ".pdf"));
        this.update(new LambdaUpdateWrapper<Report>().set(Report::getReportPath, savePath + ".docx").set(Report::getPdfPath, savePath + ".pdf").eq(Report::getId, id));
        return RequestUtils.getBasePath(request) + "upload/temp/" + report.getProductName() + fileName + ".docx";
    }
}